<template>
  <eui-background type="common">
    <eui-nav-bar title="任务详情" color="#FFFFFF" rightIcon="" />
    <view class="top-title-view" v-if="showRelatedBill">
      <view class="top_tip">
        <view style="margin-left:20rpx">
          <eui-uicons size='28' fontFamily="enjoyIcon5" :customPrefix="topTitleInfo.icon"
                      :color="topTitleInfo.iconColor" />
        </view>
        <view class="top_tip_title" :style="{color:topTitleInfo.titleColor}">{{topTitleInfo.title}}</view>
      </view>
    </view>
    <view v-if="showRelatedBill" class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <view class="main-view">
          <view class="top-view">
            <view class="flex-start-center">
              <eui-uicons v-if="showIcon(mainData)?.show" size='28' fontFamily="enjoyIcon5"
                          :customPrefix="showIcon(mainData)?.icon" :color="showIcon(mainData)?.iconColor" />
              <text class="time-title-text"
                    :style="{color:getTimeTitleColor(mainData)}">{{ mainData.c_time }}分钟</text>
              <view class="date-view">
                <text
                    class="date-text">{{ dayjs(mainData.c_plan_begin_time).format('MM-DD HH:mm') }} ~ {{ dayjs(mainData.c_require_complete_time).format('MM-DD HH:mm') }}</text>
              </view>
            </view>
            <view class="top-right">
              <eui-tag v-if="mainData.c_level_name==='初级'" type="primary" :text="mainData.c_level_name"
                       plain plainFill :showBorder="false"></eui-tag>
              <eui-tag v-if="mainData.c_level_name==='中级'" type="warning" :text="mainData.c_level_name"
                       plain plainFill :showBorder="false"></eui-tag>
              <eui-tag v-if="mainData.c_level_name==='高级'" type="error" :text="mainData.c_level_name"
                       plain plainFill :showBorder="false"></eui-tag>
              <eui-tag v-if="mainData.c_class_name" :text="mainData.c_class_name" :bgColor="themeColor"
                       :color="themeColor" :borderColor="themeColor" plain plainFill
                       :showBorder="false"></eui-tag>
            </view>
          </view>
          <view class="center-view">
            <eui-uicons v-if="mainData.c_timeliness==='T1'" size='28' fontFamily="enjoyIcon5"
                        customPrefix="icon-jinji1" color="#FF4000" />
            <view class="title-view" :style="{marginLeft:mainData.c_timeliness!=='T1'?'0rpx':'8rpx'}">
              {{ mainData.c_title }}
            </view>
          </view>
          <!-- <view class="content-view">{{ mainData.c_depiction }}</view> -->
          <view class="bottom-view">
            <eui-tag size="medium" v-if="mainData.c_recv_adno_name" :text="mainData.c_recv_adno_name"
                     :bgColor="themeColor" :color="themeColor" :borderColor="themeColor" plain
                     plainFill></eui-tag>
            <eui-tag v-if="mainData.c_importance_name==='一般'" type="primary"
                     :text="mainData.c_importance_name" plain plainFill :showBorder="false"></eui-tag>
            <eui-tag v-if="mainData.c_importance_name==='比较重要'" type="warning"
                     :text="mainData.c_importance_name" plain plainFill :showBorder="false"></eui-tag>
            <eui-tag v-if="mainData.c_importance_name==='重要'" type="error"
                     :text="mainData.c_importance_name" plain plainFill :showBorder="false"></eui-tag>
          </view>
        </view>
        <view class="card">
          <view class="talk-content-title">任务详情</view>
          <eui-card-input title="" v-model="mainData.c_depiction" placeholder="" type="textarea"
                          maxlength="500" displayable="false" :showBottomLine="false" />
        </view>
        <view class="card">
          <view class="talk-content-image">图片详情</view>
          <view style="padding:28rpx;" v-if="fileList.length>0">
            <eui-file-picker v-model="fileList" fileMediatype="image" mode="grid" :image-styles='imageStyle'
                             readonly>
            </eui-file-picker>
          </view>
          <view v-else>
            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
            <view class="no-data-text">暂无图片</view>
          </view>
        </view>

        <view class="card" v-if="showFinish">
          <view class="finish-content">任务完成情况</view>
          <eui-card-input :required="true" maxlength="4" v-model="finishData.c_total_time" title="用时(分钟)"
                          type="number" @confirm="validateDetail" fieldName="c_total_time" isBlur />
          <eui-card-input :required="true" maxlength="4" v-model="finishData.c_progress" title="完成进度(%)"
                          type="number" @confirm="validateDetail" fieldName="c_progress" isBlur />
          <eui-card-input v-model="finishData.c_done_record" title="完成记录" type="textarea" maxlength="250" />
          <eui-card-input v-model="finishData.c_undone_record" title="未完成说明" type="textarea"
                          maxlength="250" />

        </view>
        <view class="card" v-if="showFinish">
          <view class="finish-content">完成文件记录</view>
          <view style="padding:0rpx 0rpx 0rpx 28rpx">
            <eui-file-picker ref="uploadRef" v-model="finishFileList" mode="grid" file-mediatype="image"
                             :image-styles="imageStyle" :autoUpload="false" return-type="array" @select="selectPic"
                             @delete="deletePic">
              <view class="m-image-btn">
                <view class="m-image-view" />
                <text class="m-image-text">上传图片</text>
              </view>
            </eui-file-picker>
          </view>
        </view>
      </scroll-view>
    </view>

    <view v-if="!showRelatedBill && showRelatedFlag">
      <view class="related-bill-card">
        <view class="finish-content">关联单据[验收单]</view>
        <view style="padding: 0rpx 28rpx 0rpx 0rpx;" @click="relatedDownIconClick">
          <eui-uicons size='28' fontFamily="enjoyIcon5" customPrefix="icon-jiantouxiangxia" color="#333333" />
        </view>
      </view>
      <view style="margin-bottom: 40rpx;" :style="{ height: (listHeight-100) + 'rpx' }" >
        <scroll-view scroll-y="true" style="height: 100%;">
          <view class="list_cell">
            <view class="title-view">
              <text class="title-text">{{ RelatedBillData.c_id }}</text>

              <view class="temple-view" />
              <!-- 审核：[0]尚未审核 [2]预审核 [3]已审核 [5]已生效 [6]已结束 [7]已终止 [8]已完成 [9]已作废-->
              <!-- 审批：[1]尚未审批 [2]正在审批 [3]审批已通过 [4]审批未通过-->
              <eui-status v-if="RelatedBillData.c_status === '0' || RelatedBillData.c_status === '1'"
                          type="primary" :title="getStatus(RelatedBillData)" />
              <eui-status v-else-if="RelatedBillData.c_status === '2'" type="warning"
                          :title="getStatus(RelatedBillData)" />
              <eui-status
                  v-else-if="RelatedBillData.c_status === '3' || RelatedBillData.c_status === '5' || RelatedBillData.c_status === '8'"
                  type="success" :title="getStatus(RelatedBillData)" />
              <eui-status
                  v-else-if="RelatedBillData.c_status === '4' || RelatedBillData.c_status === '6' || RelatedBillData.c_status === '7'"
                  type="error" :title="getStatus(RelatedBillData)" />
              <eui-status v-else-if="RelatedBillData.c_status === '9'" type="invalid"
                          :title="getStatus(RelatedBillData)" />
            </view>

            <view class="item-view">
              <view v-for="(optionItem, optionIndex) in dataOptions" :key="optionIndex"
                    class="item-detail-view" :style="{ width: optionItem.occupy ? '100%' : '50%' }">
                <text v-if="optionItem.label" class="item-text">{{ optionItem.label }}</text>
                <text class="item-text item-text-detail">{{ RelatedBillData[optionItem.name] }}</text>
              </view>
            </view>
          </view>

          <view class="card" v-for="(detailItem,detailIndex) in RelatedBillDetailData" :key="detailIndex">
            <view class="finish-content">{{detailItem.c_gds_name}}</view>
            <view class="barcode-text">{{detailItem.c_barcode}}</view>
            <view class="item-view" style="padding:16rpx 0rpx 20rpx 28rpx">
              <view v-for="(optionItem, optionIndex) in dataOptions2" :key="optionIndex"
                    class="item-detail-view" :style="{ width: detailItem.occupy ? '100%' : '50%' }">
                <text v-if="optionItem.label" class="item-text">{{ optionItem.label }}</text>
                <text class="item-text item-text-detail">{{ detailItem[optionItem.name] }}</text>
              </view>
            </view>
            <view style="background: #F9FAFC;border-radius: 10rpx;margin:0rpx 28rpx">
              <view class="item-view" style="padding:20rpx 28rpx">
                <view v-for="(optionItem, optionIndex) in dataOptions3" :key="optionIndex"
                      class="item-detail-view" :style="{ width: detailItem.occupy ? '100%' : '50%' }">
                  <text v-if="optionItem.label" class="item-text">{{ optionItem.label }}</text>
                  <text class="item-text item-text-detail">{{ detailItem[optionItem.name] }}</text>
                </view>
              </view>
            </view>

          </view>
        </scroll-view>
      </view>
      <view style="text-align: center;" v-if="RelatedBillData.c_status==='0'">
        <eui-button type="primary" title="审核" @buttonClick="auditRelatedBill"></eui-button>
      </view>

    </view>
    <view class="bottom-card" v-if="showRelatedBill && showRelatedFlag">
      <view class="finish-content">关联单据[验收单]</view>
      <view style="padding: 0rpx 28rpx 0rpx 0rpx;" @click="goToRelationReceipt">
        <eui-uicons size='28' fontFamily="enjoyIcon5" customPrefix="icon-jiantouxiangyou" color="#333333" />
      </view>
    </view>
    <view class="footer-bottom-button-view" v-if="mainData.c_status!=='2'">
      <view v-if="selType === '1'" class="footer-bottom-button-view__left-view">
        <view class="footer-bottom-button-view__left" @click="disagreeTask">
          <view style="margin-bottom: 10rpx;">
            <eui-uicons size='32' fontFamily="enjoyIcon5" color="#000000" customPrefix="icon-quxiao" />
          </view>
          <view class="footer-bottom-button-view__text">驳回</view>
        </view>
      </view>
      <view v-else class="footer-bottom-button-view__left-view">
        <view class="footer-bottom-button-view__left">
          <view class="more-option">
            <view @click="ToggleMoreOption">
              <view style="margin-bottom: 10rpx;">
                <eui-uicons size='32' fontFamily="enjoyIcon5" color="#000000"
                            customPrefix="icon-gengduo2" />
              </view>
              <view class="footer-bottom-button-view__text">更多</view>
            </view>
            <view class="more-option-content" v-show="MoreOption">
              <view class="more-option-ul">
                <view class="more-option-list" @click="CancelTask">作废</view>
                <view class="more-option-list" @click="TopTask">置顶</view>
              </view>
              <view class="triangle-down"></view>
            </view>
          </view>
        </view>
        <view class="footer-bottom-button-view__left" @click="DelayTask">
          <view style="margin-bottom: 10rpx;">
            <eui-uicons size='32' fontFamily="enjoyIcon5" color="#000000" customPrefix="icon-yanshi" />
          </view>
          <view class="footer-bottom-button-view__text">延时</view>
        </view>
      </view>
      <view class="center-style"
            v-if="(mainData.c_progress<100 && mainData.c_progress>=0)|| !mainData.hasOwnProperty('c_recv_userno')">
        <eui-button type="primary" :title="showButton(mainData)"
                    @buttonClick="buttonClick(showButton(mainData))"></eui-button>
      </view>
    </view>
    <eui-popup ref="popupDelay" background-color="#f8f8f8" type="center" :mask-click="true" :animation="false">
      <view class="popup-delay">
        <TaskDelay :taskId="taskId" :taskMode="taskMode" @hidePopup="hideDelayPopup"
                   @closePopup="closeDelayPopupp" :hasStart="hasStart" />
      </view>
    </eui-popup>
    <eui-popup ref="popupAdjust" background-color="#f8f8f8" type="center" :mask-click="true" :animation="false">
      <view class="popup-adjust">
        <TaskAdjust :formatData="adjustData" @hidePopup="hideAdjustPopup" @clickFunc="clickAdjustPopup"
                    @userFunc="selectUser" />
      </view>
    </eui-popup>
  </eui-background>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import dayjs from 'dayjs';
import { onLoad } from "@dcloudio/uni-app";
import { storeToRefs } from 'pinia';
import { useThemeStore } from '@/store/themeStore';
import useService from '@/hooks/useService';
import { useMainStore } from "@/store/modules/store";
import TaskDelay from './components/taskDelay.vue'
import TaskAdjust from './components/taskAdjust.vue'
import Guid from '@/common/guid';
import useUpload from '@/hooks/useUpload';
const { upload, remove, fetchFile } = useUpload({ prefix: 'mainApi' });
const mainService = useService({ prefix: "mainApi" });
const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);
const themeColor = ref(theme._object.theme == 'theme-blue' ? '#02B7E6' : '#FF6430')
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const topTitleInfo = ref({
  icon: 'icon-wenxintishi',
  iconColor: '#00AD60',
  title: '任务时间充裕，请注意时间。',
  titleColor: '#00AD60',
  viewBgColor: 'rgba(0,173,96,0.05)'
})
const mainData = ref({});
const finishData = ref({
  c_total_time: 0,  //用时（分钟）
  c_progress: 100,   //完成进度（%）
  c_done_record: '',  //完成记录
  c_undone_record: '',//未完成说明
  c_done_file_id: Guid.NewGuid().ToString(),//完成文件记录
  c_undone_file_id: Guid.NewGuid().ToString() //未完成文件记录
});
const adjustData = ref({
  personName: '', // 处理人
  personId: '', //
  costTime: 30, // 预估时间
  startTime: '', // 开始时间
  endTime: '', // 结束时间
})
const showFinish = ref(false);
const taskId = ref(0);
const taskMode = ref('1');
const hasStart = ref(false);
const selType = ref('');
const taskUserNo = ref(''); //任务处理人
const taskBillId = ref(''); //单据号
const taskBillType = ref(''); //单据类型
const listHeight = ref(300);
const fileList = ref([]);
const finishFileList = ref([]);
const MoreOption = ref(false);
// 弹框
const popupDelay = ref(null);
const popupAdjust = ref(null);
const imageStyle = ref({
  "height": '200rpx',	// 边框高度
  "width": '200rpx',	// 边框宽度
  "border": {
    "color": "#EEEEEE",
    "width": "1rpx",
    "style": "dashed",
    "radius": "10rpx"
  }
})
const assignUserNo = ref('');
const showRelatedBill = ref(true);
const showRelatedFlag = ref(false);
const RelatedBillData = ref(
    {
      c_id: 'BS02212070001',
      c_status: '0',
      c_out_store_name: '[088949]小王子商贸有限公司',
      c_adno_name: '[01]昂捷信息',
      c_wno_name: '[02]本部',
      c_bhqx: '普通补货',
      c_apply_money: 601.00,
      c_create_info: '[0676]小陈   2023-11-08 10:05:30'
    }
)
const dataOptions = ref([
  { label: "机构", name: "c_out_store_name", occupy: true },
  { label: "部门", name: "c_adno_name" },
  { label: "仓库", name: "c_wno_name" },
  { label: "补货权限", name: "c_bhqx" },
  { label: "申请金额", name: "c_apply_money" },
  { label: "录入", name: "c_create_info", occupy: true },
])
const RelatedBillDetailData = ref([
      {
        c_gds_name:'[023003]陕西洛川苹果',
        c_barcode:'6920024552825',
        c_adno_name: '[111]水果',
        c_logistics_type: '直送',
        c_class_name: '[111012]苹果',
        c_yk_type: '无',
        c_bz_unit:'1.000/KG',
        c_js_ls:'6/0.000',
        c_apply_count:36.000,
        c_fee_count:0.000,
        c_ys_count:36.000,
        c_settle_money:936.000
      },
      {
        c_gds_name:'[023004]山东烟台苹果',
        c_barcode:'6920024557865',
        c_adno_name: '[111]水果',
        c_logistics_type: '直送',
        c_class_name: '[111012]苹果',
        c_yk_type: '无',
        c_bz_unit:'2.000/KG',
        c_js_ls:'6/2.000',
        c_apply_count:39.000,
        c_fee_count:2.000,
        c_ys_count:44.000,
        c_settle_money:1936.000
      },
    ]
)
const dataOptions2 = ref([
  { label: "部门", name: "c_adno_name" },
  { label: "物流方式", name: "c_logistics_type" },
  { label: "品类", name: "c_class_name" },
  { label: "越库类型", name: "c_yk_type" },
])
const dataOptions3 = ref([
  { label: "包装/单位", name: "c_bz_unit" },
  { label: "件数/零数", name: "c_js_ls" },
  { label: "申请数量", name: "c_apply_count" },
  { label: "赠品数量", name: "c_fee_count" },
  { label: "验收数量", name: "c_ys_count" },
  { label: "结算金额", name: "c_settle_money" },
])
const ToggleMoreOption = () => {
  MoreOption.value = !MoreOption.value;
}
onMounted(async () => {
  await getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      let defHeight = showRelatedFlag.value ? 240 : 120;
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - (data?.top || 0);
        //转换rpx
        let finalHeight = height / (res.windowWidth / 750) - defHeight;
        listHeight.value = finalHeight;
      }).exec()
    }
  });
}

const relatedUpIconClick = () => {
  showRelatedBill.value = false;
}
const relatedDownIconClick = () => {
  showRelatedBill.value = true;
}
//查看关联单据
const goToRelationReceipt = () => {
  uni.navigateTo({
    url: `./relation/relationReceipt?BillId=${taskBillId.value}&BillType=${taskBillType.value}`
  });
}
const getTimeTitleColor = (item) => {
  let color = "#02B7E6";
  if (!item.hasOwnProperty('c_recv_userno')) {
    if (item.c_delay_status !== '2' && item.c_delay_status !== '4') {
      color = "#02B7E6";
    }
    if (item.c_delay_status === '2' || item.c_delay_status === '4') {
      color = "#FF4000";
    }
  }
  else {
    if (item.c_delay_status !== '2' && item.c_delay_status !== '4') {
      color = "#FF7E00";
    }
    if (item.c_delay_status === '2' || item.c_delay_status === '4') {
      color = "#FF4000";
    }
  }
  return color;
}

const showButton = (item) => {
  let buttonText = "";
  if (selType.value === "1") {
    return "领取转单"
  }
  if (!item.hasOwnProperty('c_recv_userno')) {
    if (item.c_delay_status !== '2' && item.c_delay_status !== '4') {
      if (item.c_distribute_mode === 'D0') {
        buttonText = "指派"
      }
      else if (item.c_distribute_mode === 'D2') {
        buttonText = "抢单";
      }
      else {
        buttonText = "置顶";
      }
    }
    if (item.c_delay_status === '2' || item.c_delay_status === '4') {
      buttonText = "置顶";
    }
  }
  else {
    if (item.c_recv_userno) {
      if (item.c_progress === 0) {
        //当前登录人=item.c_recv_userno
        buttonText = "开始处理";
      }
      else if (item.c_progress > 0 && item.c_progress < 100) {
        buttonText = "已完成";
      }
    }
  }
  return buttonText;
}

const showIcon = (item) => {
  let iconInfo = {
    show: false,
    icon: '',
    iconColor: ''
  }
  if (!item.hasOwnProperty('c_recv_userno')) {
    if (item.c_delay_status !== '2' && item.c_delay_status !== '4') {
      iconInfo.show = true;
      iconInfo.icon = 'icon-yugu';
      iconInfo.iconColor = '#02B7E6';
    }
    else {
      if (item.c_delay_status === '4') {
        iconInfo.show = true;
        iconInfo.icon = 'icon-jingbao';
        iconInfo.iconColor = '#FF4000';
      }
    }
  }
  else {
    if (item.c_delay_status === '2' || item.c_delay_status === '4') {
      iconInfo.show = true;
      iconInfo.icon = 'icon-jingbao';
      iconInfo.iconColor = '#FF4000';
    }
    else {
      iconInfo.show = item.c_recv_userno === loginInfo.sUser && item.c_delay_status !== '2' && item.c_delay_status !== '4';
      iconInfo.icon = 'icon-shijian2';
      iconInfo.iconColor = '#FF7E00';
    }
  }
  return iconInfo;
}

onLoad(async ({ TaskId, selectType, UserNo, BillId, BillType }) => {
  taskId.value = TaskId;
  selType.value = selectType;
  taskUserNo.value = UserNo;
  taskBillId.value = BillId;
  taskBillType.value = BillType;
  showRelatedFlag.value = !!(BillId && BillType);

  if (selType.value === "0") {
    await FetchTaskAllotItem();
  }
  else {
    await FetchToDoTaskItem();
  }
})

const showAdjustPopup = async () => {
  popupAdjust.value.open('center');
}
const hideAdjustPopup = () => {
  popupAdjust.value.close();
}
const clickAdjustPopup = async () => {
  popupAdjust.value.close();
  await AssignTask();
}
const selectUser = () => {
  const selectType = "指派"
  uni.navigateTo({
    url: `./modals/taskSlgSelUser?taskId=${taskId.value}&selectType=${selectType}`
  });
}
const SelectionChanged = async (selectType, item) => {
  adjustData.value.personName = item.Value;
  adjustData.value.personId = item.Key;
}

//任务单明细 待指派的
const FetchTaskAllotItem = async () => {
  uni.showLoading({ title: "查询中...", mask: true });
  const res = await mainService.request('taskallot', 'FetchTaskAllotItem', taskId.value);
  uni.hideLoading();
  await setMainData(res);
}
// 任务单明细 待办任务
const FetchToDoTaskItem = async () => {
  uni.showLoading({ title: "查询中...", mask: true });
  const res = await mainService.request('tasktodo', 'FetchToDoTaskItem', { TaskCode: taskId.value, TaskRecvUserNo: taskUserNo.value });
  uni.hideLoading();
  console.log('FetchToDoTaskItemFetchToDoTaskItem',res)
  res.c_recv_userno=loginInfo.sUser;
  console.log('hhhhhhhhhh',res)
  await setMainData(res);
}

const setMainData = async (res : any) => {
  mainData.value = res;
  if (mainData.value.c_delay_status === '2') {
    topTitleInfo.value = {
      icon: 'icon-shijian2',
      iconColor: '#FF7E00',
      title: '任务即将过期，请注意时间。',
      titleColor: '#FF7E00',
      viewBgColor: 'rgba(255, 126, 0, 0.05)'
    }
  }
  else if (mainData.value.c_delay_status === '4') {
    topTitleInfo.value = {
      icon: 'icon-jinggao1',
      iconColor: '#FF4000',
      title: '任务已经过期，请尽快进行处理。',
      titleColor: '#FF4000',
      viewBgColor: 'rgba(255, 64, 0, 0.05)'
    }
  }
  else {
    topTitleInfo.value = {
      icon: 'icon-wenxintishi',
      iconColor: '#00AD60',
      title: '任务时间充裕，请注意时间。',
      titleColor: '#00AD60',
      viewBgColor: 'rgba(0,173,96,0.05)'
    }
  }
  if (mainData.value.hasOwnProperty('c_recv_userno') && mainData.value.c_recv_userno === loginInfo.sUser && mainData.value.c_progress<100 && selType.value !== "1") {
    showFinish.value = true;
  }
  if(mainData.value.c_progress>0){
    hasStart.value = true;
  }
  adjustData.value.personName = "";
  adjustData.value.personId = ""
  adjustData.value.costTime = mainData.value.c_time;
  adjustData.value.startTime = mainData.value.c_plan_begin_time;
  adjustData.value.endTime = mainData.value.c_require_complete_time;
  await FetchTaskFile();
}

const FetchTaskFile = async () => {
  const fileid = mainData.value.c_guid;
  const res = await mainService.request('taskmanager', 'FetchTaskFile', { FileId: fileid });
  if (res) {
    fileList.value = res.map(x => {
      return {
        name: x.c_file_name,
        extname: x.c_file_ext,
        url: mainService.getBaseUrl() + '/File/DownLoadFile/' + x.c_guid,
        c_guid: x.c_guid
      }
    })
  }
}

const DelayTask = async () => {
  MoreOption.value = false;
  if (mainData.value.hasOwnProperty('c_recv_userno') && mainData.value.c_recv_userno === loginInfo.sUser) {
    taskMode.value = "5";
  }
  else {
    taskMode.value = "1";
  }
  popupDelay.value.open('center');
}

const hideDelayPopup = async () => {
  if (selType.value === "0") {
    await FetchTaskAllotItem();
  }
  else {
    await FetchToDoTaskItem();
  }
}

const closeDelayPopupp = async () => {
  popupDelay.value.close();
}
//置顶
const TopTask = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  const req = [taskId.value];
  const res = await mainService.request('taskallot', 'TopTask', req);
  uni.hideLoading();
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '置顶成功'
  });
  MoreOption.value = false;
  setTimeout(async () => {
    if (selType.value === "0") {
      await FetchTaskAllotItem();
    }
    else {
      await FetchToDoTaskItem();
    }
  }, 1000)

}
//抢单
const ReceiveTask = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  const req = [taskId.value];
  const res = await mainService.request('taskallot', 'ReceiveTask', req);
  uni.hideLoading();
  if (res && res.length > 0) {
    if (res[0].ErrorMsg) {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: res[0].ErrorMsg
      });
    }
    else {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: '抢单成功'
      });
      setTimeout(async () => {
        uni.navigateBack({
          delta: 1
        });
      }, 2000)
    }
  }
  else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '抢单失败'
    });
  }
}
//指派
const AssignTask = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  const req = [{
    TaskId: taskId.value,
    TaskUserNo: adjustData.value.personId  //选择的人员编码
  }];
  const res = await mainService.request('taskallot', 'AssignTask', req);
  uni.hideLoading();
  if (res && res.length > 0) {
    if (res[0].ErrorMsg) {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: res[0].ErrorMsg
      });
    }
    else {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: '指派成功'
      });
      setTimeout(async () => {
        uni.navigateBack({
          delta: 1
        });
      }, 2000)
    }
  }
  else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '指派失败'
    });
  }
}
const CommitTaskBeginRecord = async()=>{
  const req = {
    c_done_file_id: finishData.value.c_done_file_id,
    c_done_record: '开始处理任务',
    c_dt: dayjs(new Date(), 'YYYY-MM-DD HH:mm:ss'),
    c_progress: 1,
    c_task_code: taskId.value,
    c_total_time: 1,
    c_undone_file_id: finishData.value.c_undone_file_id,
    c_undone_record: ''
  }
  uni.showLoading({ title: "处理中...", mask: true });
  const res = await mainService.request('tasktodo', 'CommitTaskComplateRecord', req);
  uni.hideLoading();
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '处理成功'
  });
  setTimeout(async () => {
    await FetchToDoTaskItem();
    finishData.value = {
      c_total_time: 0,  //用时（分钟）
      c_progress: 100,   //完成进度（%）
      c_done_record: '',  //完成记录
      c_undone_record: '',//未完成说明
      c_done_file_id: Guid.NewGuid().ToString(),//完成文件记录
      c_undone_file_id: Guid.NewGuid().ToString() //未完成文件记录
    };
    finishFileList.value = [];
  }, 1000)
}
//开始处理&完成
const CommitTaskComplateRecord = async () => {
  if (finishData.value.c_total_time === "") {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '任务用时不能为空'
    });
    return;
  }
  if (finishData.value.c_total_time <= 0) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '任务用时不能小于等于0'
    });
    return;
  }
  if (finishData.value.c_total_time > 9999) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '任务用时不能大于9999'
    });
    return;
  }
  if (finishData.value.c_progress === '') {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '完成进度不能为空'
    });
    return;
  }
  if (finishData.value.c_progress <= 0) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '完成进度不能小于等于0'
    });
    return;
  }
  if (finishData.value.c_progress > 100) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '完成进度不能大于100'
    });
    return;
  }
  const req = {
    c_done_file_id: finishData.value.c_done_file_id,
    c_done_record: finishData.value.c_done_record || '',
    c_dt: dayjs(new Date(), 'YYYY-MM-DD HH:mm:ss'),
    c_progress: finishData.value.c_progress,
    c_task_code: taskId.value,
    c_total_time: finishData.value.c_total_time,
    c_undone_file_id: finishData.value.c_undone_file_id,
    c_undone_record: finishData.value.c_undone_record || ''
  }
  uni.showLoading({ title: "处理中...", mask: true });
  const res = await mainService.request('tasktodo', 'CommitTaskComplateRecord', req);
  uni.hideLoading();
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '处理成功'
  });
  setTimeout(async () => {
    await FetchToDoTaskItem();
    finishData.value = {
      c_total_time: 0,  //用时（分钟）
      c_progress: 100,   //完成进度（%）
      c_done_record: '',  //完成记录
      c_undone_record: '',//未完成说明
      c_done_file_id: Guid.NewGuid().ToString(),//完成文件记录
      c_undone_file_id: Guid.NewGuid().ToString() //未完成文件记录
    };
    finishFileList.value = [];
  }, 1000)
}
const validateDetail = async (args) => {
  const { type, fieldName, oldValue, newValue, itemIndex } = args;
  switch (fieldName) {
    case 'c_total_time':
      const recN = newValue;
      if (recN <= 0) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '用时不能小于等于0'
        });
        return false;
      }
      finishData.value.c_total_time = Math.round(recN);
      break;
    case 'c_progress':
      const recPro = newValue;
      if (recPro <= 0) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '完成进度不能小于等于0'
        });
        return false;
      }
      finishData.value.c_progress = Math.round(recPro);
      break;
  }
}
const buttonClick = async (buttonText) => {
  console.log('buttonClick', buttonText);
  MoreOption.value = false;
  switch (buttonText) {
    case '指派':
      await showAdjustPopup();
      //await AssignTask();
      break;
    case '抢单':
      await ReceiveTask();
      break;
    case '置顶':
      await TopTask();
      break;
    case '开始处理':
      await CommitTaskBeginRecord();
      break;
    case '已完成':
      await CommitTaskComplateRecord();
      break;
    case '领取转单':
      await agreeTask();
      break;
  }
}
//领取转单
const agreeTask = async () => {
  uni.showModal({
    title: ' 提示',
    content: '请您确认是否同意接收所选任务？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: "处理中...", mask: true });
        const req = [mainData.value.c_deliver_to_guid];
        const res = await mainService.request('taskdelivertodo', 'AgreeTaskDeliver', req);
        uni.hideLoading();
        if (res && res.length > 0) {
          if (res[0].Msg) {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: res[0].Msg
            });
          } else {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: '领取转交成功！'
            });
            setTimeout(async () => {
              uni.navigateBack({
                delta: 1
              });
            }, 1000)
          }
        } else {
          uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '领取转交失败！'
          });
        }
      }
    }
  });
}
//驳回转单
const disagreeTask = async () => {
  uni.showModal({
    title: ' 提示',
    content: '请您确认是否驳回所选任务的转交？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: "处理中...", mask: true });
        const req = [mainData.value.c_deliver_to_guid];
        const res = await mainService.request('taskdelivertodo', 'RejectTaskDeliver', req);
        uni.hideLoading();
        if (res && res.length > 0) {
          if (res[0].Msg) {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: res[0].Msg
            });
          } else {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: '驳回转交成功！'
            });
            setTimeout(async () => {
              uni.navigateBack({
                delta: 1
              });
            }, 1000)
          }
        } else {
          uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '驳回转交失败！'
          });
        }
      }
    }
  });
}
//作废
const CancelTask = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  const req = [taskId.value];
  const res = await mainService.request('taskallot', 'CancelTask', req);
  console.log('CancelTask', res)
  uni.hideLoading();
  MoreOption.value = false;
  if (res && res.length > 0) {
    if (res[0].ErrorMsg) {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: res[0].ErrorMsg
      });
    }
    else {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: '作废成功'
      });
      MoreOption.value = false;
      setTimeout(async () => {
        if (selType.value === "0") {
          await FetchTaskAllotItem();
        }
        else {
          await FetchToDoTaskItem();
        }
      }, 1000)
    }
  }
  else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '作废失败'
    });
  }
}

//上传文件
const selectPic = async (e) => {
  const lists = e.tempFiles || [];
  const extendInfo = JSON.stringify({
    BillId: finishData.value.c_done_file_id
  });
  for (let i = 0; i < lists.length; i++) {
    const file = lists[i];
    const result = await upload({
      file: {
        ext: file.extname,
        url: file.url,
        name: file.name,
        type: file.fileType,
        guid: Guid.NewGuid().ToString()
      },
      uploadUserNo: loginInfo.sUser,
      extendInfo: extendInfo,
      UploadMethodName: 'UploadDoneTaskFileRecord',
      UniqueKey: 'taskadjust',
      ModuleCode: 'tasktodo'
    });
  }
  await FetchTaskComplatedRecord()
}
const FetchTaskComplatedRecord = async () => {
  const res = await mainService.request('taskadjust', 'FetchTaskComplatedRecord', { FileId: finishData.value.c_done_file_id });
  if (res) {
    finishFileList.value = res.map(x => {
      return {
        name: x.c_file_name,
        extname: x.c_file_ext,
        url: mainService.getBaseUrl() + '/File/DownLoadFile/' + x.c_guid,
        c_guid: x.c_guid
      }
    })
  }
}
const deletePic = async (e) => {
  const fileguid = finishFileList.value[e.index].c_guid;
  const res = await mainService.request('taskadjust', 'DeleteTaskComplatedRecord', fileguid);
  await FetchTaskComplatedRecord();
}

const getStatus = (item) => {
  // 审核：[0]尚未审核 [2]预审核 [3]已审核 [5]已生效 [6]已结束 [7]已终止 [8]已完成 [9]已作废
  // 审批：[1]尚未审批 [2]正在审批 [3]审批已通过 [4]审批未通过
  switch (item.c_status) {
    case '0':
      return '尚未审核';
    case '1':
      return '尚未审批';
    case '2':
      return '预审核';
    case '3':
      return '已审核';
    case '4':
      return '审批未通过';
    case '5':
      return '已生效';
    case '6':
      return '已结束';
    case '7':
      return '已终止';
    case '8':
      return '已完成';
    case '9':
      return '已作废';
  }
}
const auditRelatedBill = async()=>{
  RelatedBillData.value.c_status="3";
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '审核成功！'
  });
}
defineExpose({
  SelectionChanged
})
</script>
<style lang="scss" scoped>
@import '../../../main.scss';
@import '../../../static/font/enjoyicon5.0/iconfont.css';

.main-view {
  border-radius: 20rpx;
  margin: 0 20rpx 20rpx 20rpx;
  background: #FFFFFF;
  padding: 28rpx
}

.footer-view {
  width: 100%;
}

.list-scroll {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.flex-start-center {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.top-title-view {
  background: #FFFFFF;
  border-radius: 10rpx;
  margin: 20rpx;
}

.top_tip {
  background: rgba(0, 173, 96, 0.05);
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;

  .top_tip_title {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 20rpx;
    margin-left: 8rpx;
    color: #666666;
    line-height: 42rpx;
    text-align: left;
    font-style: normal;
  }
}

//顶部行
.top-view {
  display: flex;
  width: 100%;
  height: 46rpx;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.center-view {
  display: flex;
  width: 100%;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20rpx;
}

.bottom-view {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  //margin-bottom: 23rpx;
  //margin-left: 20rpx;
}

.bottom-button-view {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0rpx 0rpx 0rpx;

  &__left {
    text-align: center;
  }

  &__right {
    margin-left: 42rpx;
  }

  &__text {
    font-family: $uni-font-family;
    color: #000000;
    font-size: 16rpx;
    line-height: 22rpx;
    font-style: normal;
  }
}

.top-right {
  margin-right: -28rpx;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.title-view {
  display: flex;
  width: 100%;
  font-size: 28rpx;
  line-height: 39rpx;
  font-weight: blod;
  flex-direction: row;
  align-items: center;
  margin-left: 8rpx;
}

.content-view {
  font-size: 20rpx;
  line-height: 30rpx;
  color: #888888;
  margin-bottom: 20rpx;
  text-align: justify;
  font-style: normal;
}

.time-title-text {
  font-family: $uni-font-family;
  color: #02B7E6;
  font-weight: 500;
  font-size: 20rpx;
  line-height: 28rpx;
  text-align: left;
  font-style: normal;
  margin-top: 0;
  margin-left: 8rpx;
}


.date-view {
  display: flex;
  justify-content: center;
  align-items: center;
  // height: 32rpx;
  margin: 0 0rpx 0 12rpx;
}

.date-text {
  font-family: $uni-font-family;
  font-size: 20rpx;
  font-weight: 400;
  color: #888888;
  line-height: 28rpx;
  text-align: left;
  font-style: normal;
}

.card {
  border-radius: 20rpx;
  margin: 0 20rpx 20rpx 20rpx;
  padding: 20rpx 0rpx 20rpx 0rpx;
  margin-bottom: 20rpx;
  background: #ffffff;
}

.bottom-card {
  border-radius: 20rpx 20rpx 0rpx 0rpx;
  //margin: 0 20rpx 20rpx 20rpx;
  padding: 20rpx 0rpx 20rpx 0rpx;
  margin-bottom: 20rpx;
  background: #ffffff;
  bottom: 90rpx;
  position: fixed;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.talk-content {
  font-size: 30rpx;
  color: #000000;
  line-height: 42rpx;
  font-weight: 600;
  padding: 8rpx 28rpx 28rpx 28rpx;
}

.talk-content-title {
  font-size: 30rpx;
  color: #000000;
  line-height: 42rpx;
  font-weight: 600;
  margin-bottom: -20rpx;
  padding: 0rpx 0rpx 0rpx 28rpx;
}

.talk-content-image {
  font-size: 30rpx;
  color: #000000;
  line-height: 42rpx;
  font-weight: 600;
  margin-bottom: -10rpx;
  padding: 0rpx 0rpx 0rpx 28rpx;
}

.footer-bottom-button-view {
  width: 100%;
  position: fixed;
  bottom: 0;
  // height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-direction: row;
  padding: 16rpx 0rpx;

  &__left-view {
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex: 1;
  }

  &__left {
    text-align: center;
  }

  &__right {
    margin-left: 42rpx;
  }

  &__text {
    font-family: $uni-font-family;
    color: #000000;
    font-size: 16rpx;
    line-height: 22rpx;
    font-style: normal;
  }
}

.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
  //gap: 20rpx;
}

.more-option {
  position: relative;
}

.more-option-content {
  position: absolute;
  background-color: #fff;
  font-size: 13px;
  width: max-content;
  bottom: 40px;
  border-radius: 10px;
  color: #333;
  box-shadow: 0px 0px 10px rgba(136, 136, 136, 0.5);
  text-align: center;
  left: -8px;
  z-index: 9999;

  .triangle-down {
    position: absolute;
    width: 0px;
    height: 0;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-top: 10px solid white;
    z-index: 1;
    bottom: -9px;
    left: 10px;
  }
}

.more-option-content2 {
  position: absolute;
  background-color: #fff;
  font-size: 13px;
  width: max-content;
  top: 32px;
  border-radius: 10px;
  color: #333;
  box-shadow: 0px 0px 10px rgba(136, 136, 136, 0.5);
  text-align: center;
  left: -8px;
  z-index: 9999;

  .triangle-down {
    position: absolute;
    width: 0px;
    height: 0;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-bottom: 10px solid white;
    z-index: 1;
    top: -10px;
    left: 10px;
  }
}

.more-option-ul {
  padding: 0px 18rpx;
}

.more-option-list {
  padding: 15rpx 0px;
  font-size: 30rpx;
  border-bottom: solid 1px rgba(238, 238, 238, 1);
}

.more-option-list:last-child {
  border-bottom: none;
}

.image-min {
  width: 100%;
  height: 200rpx;
  opacity: 0.6;
}

.no-data-text {
  text-align: center;
  color: #cccccc;
  font-size: 24rpx;
  margin-top: -20rpx;
}

// 延期弹框
.popup-delay {
  width: 630rpx;
  // height: 645rpx;
  height: auto;
}

.m-image-btn {
  width: 148rpx;
  height: 148rpx;
  background: rgba(238, 238, 238, 0.25);
  border-radius: 10rpx;
  border: 1rpx dashed #CCCCCC;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.m-image-view {
  width: 40rpx;
  height: 37rpx;
  align-self: center;
  background-image: url(../../../static/img/imgUpload.png);
  background-size: 100% 100%;
}

.m-image-text {
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level1;
  font-size: $uni-font-size-level7;
  color: $uni-text-color-primary;
  line-height: 28rpx;
  text-align: right;
  font-style: normal;
  margin-top: 7rpx;
}

::v-deep .file-picker__box-content {
  border: none !important;
}

.related-bill-card {
  border-radius: 20rpx 20rpx 0rpx 0rpx;
  //margin: 0 20rpx 20rpx 20rpx;
  padding: 20rpx 0rpx 20rpx 0rpx;
  margin-top:48rpx;
  margin-bottom: 20rpx;
  background: #ffffff;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

// 派单框
.popup-adjust {
  width: 630rpx;
  height: 645rpx;
}
//关联单据
.list_cell {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  position: relative;
  background: $uni-bg-color-inverse;
  border-radius: 20rpx;
  margin: 0 20rpx 20rpx 20rpx;
  padding: 28rpx;
  overflow: hidden;
}

//标题行
.title-view {
  display: flex;
  width: 100%;
  height: 46rpx;
  flex-direction: row;
  align-items: center;
  //margin-bottom: 24rpx;
}

.title-text {
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level3;
  font-size: $uni-font-size-level1;
  color: $uni-text-color-primary;
  line-height: 45rpx;
  text-align: left;
  font-style: normal;
  margin-top: 0;
}
.temple-view {
  flex: 1;
}

//内容行
.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
}

.item-detail-view {
  width: 50%;
  /* 每列宽度为50% */
  height: 42rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.item-text {
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level1;
  font-size: $uni-font-size-level4;
  color: $uni-text-color-hint;
  line-height: 37px;
  text-align: left;
  font-style: normal;
  margin-right: 16rpx;
  width: auto;
}

.item-text-detail {
  color: $uni-text-color-primary;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.finish-content {
  font-size: 30rpx;
  color: #000000;
  line-height: 42rpx;
  font-weight: 600;
  margin-bottom: 10rpx;
  padding: 0rpx 0rpx 0rpx 28rpx;
}
.barcode-text{
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 24rpx;
  color: #888888;
  line-height: 33rpx;
  text-align: left;
  font-style: normal;
  padding:0rpx 0rpx 0rpx 28rpx
}
</style>
